#!/usr/bin/env python
# Copyright (C) 
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# 
##
# @file uninstall.py
# @Synopsis: A tool used to uninstall programs by manually compiling.
# @author hkuieagle
# @version 0.1
# @date 2011-09-23
# @usage run this file in the compiling directory of the program you want to uninstall
# for how me works, see http://hi.baidu.com/hkuieagle/blog/item/0dae8af73ecefa77ddc47489.html

import sys, os

PACKAGE_NAME = os.path.abspath('.').split('/')[-1]
DESTDIR = "/tmp/" + PACKAGE_NAME
MAKE_INSTALL = "make > /dev/null ; make install DESTDIR=" + DESTDIR + "> /dev/null"
FILELIST = DESTDIR + '.' + 'uninstall'
TREE = "tree -if . > " + FILELIST

print 'package name:', PACKAGE_NAME
print 'destdir:', DESTDIR
print 'filelist:', FILELIST
print

class queue(object):
    def __init__(self, filelist):
        self.f = open(filelist, 'r')
        self.lines = [line.strip()[1:] for line in self.f.readlines() if line != '\n']
        self.lines.pop()
        self.lines.append('DUMMY')

    def get(self):
        return self.lines.pop(0)

    def put(self, line):
        self.lines.append(line)

def uninstall(filelist):
    lines_queue = queue(filelist)
    reach_dummy = 0
    del_count = 0
    while True:
        l = lines_queue.get()
        if os.path.isfile(l):
            os.remove(l)
            print "Del: ", l
            del_count += 1
        elif os.path.isdir(l):
            try:
                os.rmdir(l)
                print "Del: ", l
                del_count += 1
            except OSError:
                lines_queue.put(l)
        elif l == 'DUMMY':
            reach_dummy = 1
            lines_queue.put(l)

        if reach_dummy == 1:
            if del_count == 0:
                break
            else:
                reach_dummy = 0
                del_count = 0

    print
    print "Uninstalled ", PACKAGE_NAME, " successfully!"
    return 0

os.system(MAKE_INSTALL)
os.chdir(DESTDIR)
os.system(TREE)
uninstall(FILELIST)
os.chdir('/tmp')
os.system('rm -r ' + DESTDIR)
os.system('rm ' + FILELIST)

